// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "date" | "native-date" | "image-upload" | "file-upload" | "readonly" | "department-picker" | "text" | "autocomplete" | "portrait-camera";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  popupTitle?: string; // 弹窗标题（用于department-picker类型）
  departmentData?: any[]; // 部门数据（用于department-picker类型）
  // 自动补全相关配置
  searchApi?: (query: string) => Promise<OptionItem[]>; // 自动补全搜索API
  minSearchLength?: number; // 最小搜索长度
  debounceTime?: number; // 防抖时间
  // 原生日期选择器相关属性
  startDate?: string; // 开始日期
  endDate?: string; // 结束日期
  dateFormat?: 'YYYY-MM-DD' | 'YYYY/MM/DD' | 'MM/DD/YYYY'; // 日期格式
  disabled?: boolean; // 是否禁用
  // 额外信息显示功能
  extraInfo?: (value: any, formData?: any) => string; // 计算并显示额外信息
  tips?: string; // 字段提示信息
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
  // 身份证有效期特殊标识：支持长期有效显示
  supportLongTerm?: boolean;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 应聘申请单表单配置
export const interviewFormConfig: Record<string, FieldConfig> = {
  // 应聘信息
  recruitPublishRequestBillId: {
    key: "recruitPublishRequestBillId",
    label: "招聘发布单",
    type: "readonly",
    placeholder: "招聘发布单信息",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  currentSalary: {
    key: "currentSalary",
    label: "原薪酬",
    type: "input",
    placeholder: "请输入原薪酬",
    required: false,
    inputType: "number",
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  expectedSalary: {
    key: "expectedSalary",
    label: "期望薪酬",
    type: "input",
    placeholder: "请输入期望薪酬",
    required: false,
    inputType: "number",
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 单据信息
  billCode: {
    key: "billCode",
    label: "单据编号",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  remark: {
    key: "remark",
    label: "备注",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 基本信息
  name: {
    key: "name",
    label: "姓名",
    type: "readonly",
    placeholder: "通过身份证正面照片自动识别",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  gender: {
    key: "gender",
    label: "性别",
    type: "readonly",
    placeholder: "通过身份证正面照片自动识别",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  birthDate: {
    key: "birthDate",
    label: "出生日期",
    type: "readonly",
    placeholder: "通过身份证正面照片自动识别",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  ethnicity: {
    key: "ethnicity",
    label: "民族",
    type: "readonly",
    placeholder: "通过身份证正面照片自动识别",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  highestEducation: {
    key: "highestEducation",
    label: "最高学历",
    type: "picker",
    placeholder: "请选择最高学历",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["小学", "初中", "高中", "中专", "大专", "本科", "研究生", "硕士", "博士", "博士后", "博士研究生", "其他"],
  },
  maritalStatus: {
    key: "maritalStatus",
    label: "婚姻状况",
    type: "picker",
    placeholder: "请选择婚姻状况",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["未婚", "已婚", "离异", "丧偶"],
  },
  photoId: {
    key: "photoId",
    label: "照片",
    type: "portrait-camera",
    placeholder: "请拍摄或上传照片",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "image",
      maxSize: 5,
      maxCount: 1,
      listType: "picture-card",
      tips: "请上传清晰的个人近身照片，文件大小不能超过5MB",
    },
  },
  isVeteran: {
    key: "isVeteran",
    label: "是否退伍军人",
    type: "picker",
    placeholder: "请选择是否退伍军人",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["是", "否"],
  },
  veteranCertificateId: {
    key: "veteranCertificateId",
    label: "退伍证图片",
    type: "image-upload",
    placeholder: "请上传退伍证图片",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "image",
      maxSize: 5,
      maxCount: 1,
      listType: "picture-card",
      tips: "支持jpg、png格式，文件大小不超过5MB",
    },
  },
  hasRelativeInCompany: {
    key: "hasRelativeInCompany",
    label: "亲属关系",
    type: "picker",
    placeholder: "请选择亲属关系",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["是", "否"],
    tips: "是否与本单位职工存在亲属关系",
  },
  relativeName: {
    key: "relativeName",
    label: "亲属姓名",
    type: "input",
    placeholder: "请输入亲属姓名",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    validation: (value: any, formData?: any) => {
      // 如果选择了"是"，则亲属姓名为必填
      if (formData?.hasRelativeInCompany === "是") {
        if (!value || !value.toString().trim()) {
          return { valid: false, message: "请输入亲属姓名" };
        }
      }
      return true;
    },
  },
  relationshipType: {
    key: "relationshipType",
    label: "亲属关系",
    type: "picker",
    placeholder: "请选择亲属关系",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["父亲", "母亲", "配偶", "子女", "兄弟姐妹", "其他"],
    validation: (value: any, formData?: any) => {
      // 如果选择了"是"，则亲属关系为必填
      if (formData?.hasRelativeInCompany === "是") {
        if (!value || !value.toString().trim()) {
          return { valid: false, message: "请选择亲属关系" };
        }
      }
      return true;
    },
  },
  isLaborRelationshipTerminated: {
    key: "isLaborRelationshipTerminated",
    label: "是否解除劳务合同",
    type: "picker",
    placeholder: "请选择是否解除劳务合同",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["是", "否"],
  },
  fertilityStatus: {
    key: "fertilityStatus",
    label: "生育状况",
    type: "picker",
    placeholder: "请选择生育状况",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["未育", "一育", "二育", "三育", "四育及以上"],
  },
  majorCategory: {
    key: "majorCategory",
    label: "专业大类",
    type: "picker",
    placeholder: "请选择专业大类",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["化学化工类", "工学", "理学", "医学", "农学", "管理学", "经济学", "法学", "文学", "教育学", "艺术学", "历史学", "哲学", "其他"],
  },
  majorName: {
    key: "majorName",
    label: "专业名称",
    type: "input",
    placeholder: "请输入专业名称",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  height: {
    key: "height",
    label: "身高（cm）",
    type: "input",
    placeholder: "请输入身高（cm）",
    required: true,
    inputType: "number",
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    validation: (value: any) => {
      if (!value) return { valid: false, message: "请输入身高" };
      const numValue = Number(value);
      if (isNaN(numValue) || numValue <= 0 || numValue > 250) {
        return { valid: false, message: "请输入0-250之间" };
      }
      return true;
    },
  },
  weight: {
    key: "weight",
    label: "体重（kg）",
    type: "input",
    placeholder: "请输入体重（kg）",
    required: true,
    inputType: "number",
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    extraInfo: (value: any) => {
      if (!value) return "";
      const numValue = Number(value);
      if (isNaN(numValue) || numValue <= 0) return "";
      const jin = (numValue * 2).toFixed(1);
      return `约 ${jin} 斤`;
    },
    validation: (value: any) => {
      if (!value) return { valid: false, message: "请输入体重" };
      const numValue = Number(value);
      if (isNaN(numValue) || numValue <= 0 || numValue > 150) {
        return { valid: false, message: "请输入0-150之间" };
      }
      return true;
    },
  },

  // 身份信息
  idCardNo: {
    key: "idCardNo",
    label: "身份证号",
    type: "readonly",
    placeholder: "通过身份证人像面照片自动识别",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  idCardExpiryDate: {
    key: "idCardExpiryDate",
    label: "身份证有效期",
    type: "readonly",
    placeholder: "通过身份证国徽面照片自动识别",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    // 特殊标识：支持长期有效显示
    supportLongTerm: true,
  },
  idCardFrontPhotoId: {
    key: "idCardFrontPhotoId",
    label: "身份证人像面",
    type: "image-upload",
    placeholder: "请上传身份证人像面照片（横版拍摄）",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "image",
      maxSize: 5,
      maxCount: 1,
      listType: "picture-card",
      tips: "请横向拍摄身份证人像面，确保照片清晰完整，支持jpg、png格式，文件大小不超过5MB",
    },
  },
  idCardBackPhotoId: {
    key: "idCardBackPhotoId",
    label: "身份证国徽面",
    type: "image-upload",
    placeholder: "请上传身份证国徽面照片（横版拍摄）",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "image",
      maxSize: 5,
      maxCount: 1,
      listType: "picture-card",
      tips: "请横向拍摄身份证国徽面，确保照片清晰完整，支持jpg、png格式，文件大小不超过5MB",
    },
  },

  // 户籍信息
  householdRegistration: {
    key: "householdRegistration",
    label: "户口所在地",
    type: "readonly",
    placeholder: "通过身份证人像面照片自动识别",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  politicalStatus: {
    key: "politicalStatus",
    label: "政治面貌",
    type: "picker",
    placeholder: "请选择政治面貌",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["共青团员", "中共党员", "群众", "无党派人士", "其他"],
  },

  // 联系方式
  phone: {
    key: "phone",
    label: "手机号",
    type: "input",
    placeholder: "请输入手机号",
    required: true,
    inputType: "tel",
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    pattern: "^1[3456789]\\d{9}$",
    patternErrorMessage: "请输入正确的手机号码",
  },
  homeAddress: {
    key: "homeAddress",
    label: "现住址",
    type: "textarea",
    placeholder: "请输入详细现住址（示例：XX省XX市XX区XX街道XX小区X栋X单元X室）",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 工作信息
  joinWorkDate: {
    key: "joinWorkDate",
    label: "参加工作日期",
    type: "native-date",
    placeholder: "请选择参加工作日期",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },

  // 详情页面专用字段
  billStatus: {
    key: "billStatus",
    label: "单据状态",
    type: "readonly",
    placeholder: "单据状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  workflowStatus: {
    key: "workflowStatus",
    label: "工作流状态",
    type: "readonly",
    placeholder: "工作流状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approver: {
    key: "approver",
    label: "审批人",
    type: "readonly",
    placeholder: "审批人",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalTime: {
    key: "approvalTime",
    label: "审批时间",
    type: "readonly",
    placeholder: "审批时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 面试相关信息（详情页展示）
  initialTestTime: {
    key: "initialTestTime",
    label: "初试时间",
    type: "readonly",
    placeholder: "初试时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  initialResult: {
    key: "initialResult",
    label: "初试结果",
    type: "readonly",
    placeholder: "初试结果",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  initialComment: {
    key: "initialComment",
    label: "初试评语",
    type: "readonly",
    placeholder: "初试评语",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  reExamTime: {
    key: "reExamTime",
    label: "复试时间",
    type: "readonly",
    placeholder: "复试时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  reExamResult: {
    key: "reExamResult",
    label: "复试结果",
    type: "readonly",
    placeholder: "复试结果",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  reExamComment: {
    key: "reExamComment",
    label: "复试评语",
    type: "readonly",
    placeholder: "复试评语",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  finalResult: {
    key: "finalResult",
    label: "最终结果",
    type: "readonly",
    placeholder: "最终结果",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  finalRemark: {
    key: "finalRemark",
    label: "最终评语",
    type: "readonly",
    placeholder: "最终评语",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  rejectReason: {
    key: "rejectReason",
    label: "拒绝原因",
    type: "readonly",
    placeholder: "拒绝原因",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 组织信息（详情页展示）
  orgId: {
    key: "orgId",
    label: "公司",
    type: "readonly",
    placeholder: "公司",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  groupId: {
    key: "groupId",
    label: "所属部门",
    type: "readonly",
    placeholder: "所属部门",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  jobPositionId: {
    key: "jobPositionId",
    label: "工作岗位",
    type: "readonly",
    placeholder: "工作岗位",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
};

// 表单分组配置
export const formSections: FormSection[] = [
  {
    key: "applicationInfo",
    title: "应聘信息",
    fields: [
      interviewFormConfig.recruitPublishRequestBillId,
      interviewFormConfig.currentSalary,
      interviewFormConfig.expectedSalary,
      interviewFormConfig.initialTestTime,
      interviewFormConfig.initialResult,
      interviewFormConfig.initialComment,
      interviewFormConfig.reExamTime,
      interviewFormConfig.reExamResult,
      interviewFormConfig.reExamComment,
      interviewFormConfig.finalResult,
      interviewFormConfig.finalRemark,
      interviewFormConfig.rejectReason,
    ],
  },
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      interviewFormConfig.billCode,
      interviewFormConfig.billStatus,
      interviewFormConfig.workflowStatus,
      interviewFormConfig.remark,
    ],
  },
  {
    key: "identityInfo",
    title: "身份信息",
    fields: [
      interviewFormConfig.idCardFrontPhotoId,
      interviewFormConfig.idCardBackPhotoId,
      interviewFormConfig.idCardNo,
      interviewFormConfig.idCardExpiryDate,
    ],
  },
  {
    key: "basicInfo",
    title: "基本信息",
    fields: [
      interviewFormConfig.name,
      interviewFormConfig.gender,
      interviewFormConfig.birthDate,
      interviewFormConfig.ethnicity,
      interviewFormConfig.height,
      interviewFormConfig.weight,
      interviewFormConfig.highestEducation,
      interviewFormConfig.majorCategory,
      interviewFormConfig.majorName,
      interviewFormConfig.maritalStatus,
      interviewFormConfig.fertilityStatus,
      interviewFormConfig.photoId,
      interviewFormConfig.isVeteran,
      interviewFormConfig.veteranCertificateId,
      interviewFormConfig.hasRelativeInCompany,
      interviewFormConfig.relativeName,
      interviewFormConfig.relationshipType,
      interviewFormConfig.isLaborRelationshipTerminated,
    ],
  },
  {
    key: "registrationInfo",
    title: "户籍信息",
    fields: [
      interviewFormConfig.householdRegistration,
    ],
  },
  {
    key: "politicalInfo",
    title: "政治面貌",
    fields: [
      interviewFormConfig.politicalStatus,
    ],
  },
  {
    key: "contactInfo",
    title: "联系方式",
    fields: [
      interviewFormConfig.homeAddress,
      interviewFormConfig.phone,
    ],
  },
  {
    key: "workInfo",
    title: "工作信息",
    fields: [
      interviewFormConfig.orgId,
      interviewFormConfig.groupId,
      interviewFormConfig.jobPositionId,
      interviewFormConfig.joinWorkDate,
    ],
  },
  {
    key: "workflowInfo",
    title: "流程信息",
    fields: [
      interviewFormConfig.approver,
      interviewFormConfig.approvalTime,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  return formSections
    .filter(section => {
      // 编辑页面排除单据信息分组
      if (pageType === 'edit' && section.key === 'billInfo') {
        return false;
      }
      return true;
    })
    .map(section => ({
      ...section,
      fields: section.fields.filter(field => {
        if (pageType === 'create') {
          return field.showInCreate !== false;
        } else if (pageType === 'edit') {
          return field.showInEdit !== false;
        } else if (pageType === 'details') {
          // 详情页根据showInDetails配置显示字段
          return field.showInDetails !== false;
        }
        return false;
      })
    }))
    .filter(section => section.fields.length > 0);
};

// 根据表单数据动态过滤字段（用于条件显示）
export const getFilteredFormSections = (
  sections: FormSection[],
  formData: Record<string, any>
): FormSection[] => {
  return sections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      // 退伍证照片字段只在选择"是"时显示
      if (field.key === 'veteranCertificateId') {
        return formData.isVeteran === '是';
      }
      // 亲属姓名和亲属关系字段只在选择"是"时显示
      if (field.key === 'relativeName' || field.key === 'relationshipType') {
        return formData.hasRelativeInCompany === '是';
      }
      return true;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(interviewFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};
